package Solution101_200.problem117.II116;

import common.Node;

/**
 * @program Leetcode
 * @description:
 * @author: lishangsheng
 * @create: 2019/07/17 17:57
 */
public class ErrorSolution {
    public Node connect(Node root) {
        if (root == null) {
            return null;
        }
        root.next = null;
        connectNode(root);
        return root;
    }

    private void connectNode(Node root) {
        if (root.left == null && root.right == null) {
            return;
        }
        if (root.left != null) {
            if(root.right!=null){
                root.left.next = root.right;
            }else {
                Node next=getNext(root);
                if(next==null){
                    root.left.next=null;
                }else if(next.left!=null){
                    root.left.next=next.left;
                }else {
                    root.left.next=next.right;
                }
            }
        }
        if(root.right!=null){

            Node next=getNext(root);
            if(next==null){
                root.right.next=null;
            }else if(next.left!=null){
                root.right.next=next.left;
            }else {
                root.right.next=next.right;
            }
        }
        if (root.left != null) {
            connectNode(root.left);
        }
        if (root.right != null) {
            connectNode(root.right);
        }
    }

    private Node getNext(Node node){

        if(node.next==null){
            return null;
        }
        if(node.next.right==null&&node.next.left==null){
            return getNext(node.next);
        }
        return node.next;

    }
}
